<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/26 14:53
 */

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Controllers\ModelForm;
use App\Http\Models\Goods;
use App\Http\Models\GoodsCorrection;
use App\Http\Models\GoodsCoupon;
use App\Http\Models\StatisticsGoodsInfo;
use App\Http\Models\StatisticsGoodsInfoLog;
use Auth;
use DB;
use Illuminate\Http\Request;
use function Sodium\crypto_box_publickey_from_secretkey;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Table;


class BurstingController extends Controller
{

    use ModelForm;
    protected $headerStr = '爆款';
    protected $type = 1;  //1,all_allow  通过 2,refuse 拒绝,3 未审核  ,4 lower 下架
    protected $error_id;  //纠错id
    protected $is_error = false;
    protected $gid;
    protected $goodsstate;
    protected $is_today;

    public function index()
    {
        $type = request('type');
        $this->is_today = request('today');
        $this->type = empty($type) ? 3 : ($type == 'all_allow' ? 1 : ($type == 'refuse' ? 2 : 4));
        $type = $this->type;
        return Admin::content(function (Content $content) use ($type) {
            $content->header($this->headerStr . '管理');
            $content->description(show_description($this->type, $this->is_today));
            $content->body($this->grid($type));
        });
    }

    //1,all_allow  通过 2,refuse 拒绝,3 未审核  ,4 lower 下架
    protected function grid($type)
    {
        return Admin::grid(Goods::class, function (Grid $grid) use ($type) {
            if ($type == 4 || $this->type == 4) {
                $status = [4, 6, 7, 8, 9, 10,11];
            } elseif ($type == 2 || $this->type == 2) {
                $status = [3];
            } elseif ($type == 1 || $this->type == 1) {  //
                $status = [2];
            } else {
                $status = [0];
            }
            if ($this->is_today) {
                $time_check = $this->type == 3 ? 'created_at' : 'status_time';
                $grid->model()->whereIn('goodsstate', $status)
                    ->where(['goodstype' => 1])
                    ->whereDate($time_check, date('Y-m-d'))
                    ->orderBy('status_time', 'desc');
            } elseif (in_array(3, $status)) {
                $grid->model()
                    ->whereIn('goodsstate', $status)
                    ->where(['goodstype' => 1])
                    ->orderBy('id', 'desc');
            } else {
                $grid->model()
                    ->whereIn('goodsstate', $status)
                    ->where(['goodstype' => 1])
                    ->orderBy('id', 'desc');
            }
            $grid->id('编号');
            $grid->coverimage('商品主图')->display(function ($image) {
                $image = isset($image['main']) ? all_image_url($image['main']) : '';
                //return '<img src="' . $image . '" width="50" height="50">';
                return '<img src="' . $image . '" width="120" height="120" data-url=1 class="image_show" style="margin-left:5px" onclick=showimage(' . $this->id . ',"' . $image . '")>';

            });

            $grid->goodstitle('商品信息')->display(function () {
                $couponinfo = GoodsCoupon::getGoodsCouponlink($this->id);
                $commissioninfo = commissionrateInfo($this->commissiontype, $this->commissionrate);

                $info = array
                (
                    '商品标题' => '<a target="_blank" href="' . $this->goodslink . '">' . str_limit($this->goodstitle, $limit = 30, $end = '...') . '</a>',
                    '原价/券后价' => '￥' . $this->origprice . ' / ￥' . $this->voucherprice,
                    '优惠券信息' => $couponinfo['couponlink'] ? '<a target="_blank" href="' . $couponinfo['couponlink'] . '">￥ ' . $couponinfo['couponmoney'] . '</a>' : '',
                    '佣金信息' => $commissioninfo,
                );
                return new Table([], $info);
            });

            // $grid->goodstitle('商品标题')->display(function ($value) {
            //     return '<a target="_blank" href="' . $this->goodslink . '">' . str_limit($value, $limit = 30, $end = '...') . '</a>';
            //     //return str_limit($value, $limit = 30, $end = '...');
            // });
            // $grid->voucherprice('原价 / 券后价')->display(function ($value) {
            //     return '￥' . $this->origprice . ' / ￥' . $value;
            // });
            // $grid->goodcoupon()->couponmoney('优惠券信息')->display(function ($value) {
            //     $link = GoodsCoupon::getGoodsCouponlink($this->id);
            //     return $link ? '<a target="_blank" href="' . $link . '">￥' . $value . '</a>' : '';
            // });
            // if (!in_array($this->type, [2, 4])) {
            //     $grid->begintime('开始时间')->display(function ($value) {
            //         return $this->begintimetype == 1 ? '立即开始' : $value;
            //     })->sortable();
            // }
            // $grid->commissiontype('佣金信息')->display(function () {
            //     return commissionrateInfo($this->commissiontype, $this->commissionrate);
            // });

            $grid->created_at('提交时间');
            $grid->userid('提交人(ID)')->display(function () {
                return User::getUserName($this->userid) . '(' . $this->userid . ')';
            });
            if (!in_array($this->type, [2, 4])) {
                $grid->begintime('开始时间')->display(function ($value) {
                    return $this->begintimetype == 1 ? '立即开始' : $value;
                })->sortable();
            }

            $grid->goodsstate('商品状态')->display(function ($value) {
                $str = show_goods_status_style((int)$value);
                if ($value == 3) {
                    $info = [
                        '商品状态' => $str,
                        '拒绝原因' => json_decode($this->refuse, 320)['content'],
                    ];
                    return new Table([], $info);
                }
                return $str;
            });
            if (!empty($type) && $type == 'refuse') {
                $grid->goodAudit()->content('拒绝原因');
            }
            /* if ($this->type != 3) {
                 $grid->couponstate('优惠券状态')->display(function ($released) {
                    return getCouponstateInfo($released);
                 });
             }*/

            $grid->filter(function ($filter) {
                //$filter->disableIdFilter();//禁用查询过滤器
                $filter->column(1 / 2, function ($filter) {
                    if($this->type==3){ //未审核
                        $filter->between('created_at', '提交日期')->datetime();
                    }else{
                        $filter->between('status_time', '更新日期')->datetime();
                    }
                    $filter->like('goodstitle', '商品标题');
                    if($this->type!=3){
                        $filter->where(function ($query) {
                            if ($this->input == 1) {
                                $query->whereRaw("`userid` >= 10000");
                            } else {
                                $query->whereRaw("`userid` < 10000");
                            }
                        }, '后台/采集审核')->select(['1' => '后台审核', '2' => '采集审核']);
                    }
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('userid', '用户ID');
                    $filter->equal('goodsid', '淘宝商品ID');
                    if ($this->type == 1) {
                        if ($this->type == 1) {
                            $filter->where(function ($query) {
                                if ($this->input == 0) {
                                    $query->whereRaw("`site_error_status` >={$this->input} AND `auto_error_status` = {$this->input} AND `goodsstate` = 2 ");
                                } else {
                                    $query->whereRaw("`site_error_status` >={$this->input} OR `auto_error_status` = {$this->input} OR `goodsstate` = 9 ");
                                }
                            }, '是否有错')->select(['0' => '无', '1' => '有错']);
                        }
                    }
                });

                if ($this->type == 4) {
                    $filter->equal('goodsstate', '商品状态')->select([
                        '4' => '下架',
                        '6' => '主动下架',
                        '7' => '自动采集删除',
                        '8' => '采集下架',
                        '9' => '机器纠错',
                        '10' => '优惠券过期',
                    ]);
                }
            });
            if (!empty($type) && $type == 'all_allow') {
                $grid->column('is_error', '待纠错')->display(function () {
                    if ($this->site_error_status == 1 && $this->auto_error_status == 1) {
                        return '<span class=" label label-warning">人工/机器</span>';
                    } elseif ($this->site_error_status == 1) {
                        return '<span class=" label label-warning">人工错误</span>';
                    } elseif ($this->auto_error_status == 1) {
                        return '<span class=" label label-warning">机器错误</span>';
                    } else {
                        return '无';
                    }
                });
            }


            $grid->actions(function ($actions) use ($type) {
                if (Admin::user()->isRole('administrator')) {
                    $actions->disableDelete();
                } elseif (Admin::user()->isRole('bursting') && $type == 3) {
                    $actions->append('<a href="javascript:void(0)" class="btn btn-success"  title="审核通过" onclick="checkGood(' . $actions->getKey() . ',2)">通过</a>');
                    $actions->append('<a href="javascript:void(0)" class="btn btn-danger"  style="margin-left:15px;"  title="审核拒绝" onclick="showCloseReason(' . $actions->getKey() . ')">打回</a>');
                    $actions->disableEdit();
                    $actions->disableDelete();
                } elseif (Admin::user()->isRole('bursting') && $type == 1) {
                    $actions->append('<a class="btn btn-danger" href="javascript:void(0)"  title="下架" onclick="LowerCheckGood(' . $actions->getKey() . ',4)">下架</a>');
                    $actions->disableEdit();
                    $actions->disableDelete();
                } else {
                    $actions->disableDelete();
                    $actions->disableEdit();
                }
                if (method_exists($actions, 'disableView')) {
                    $actions->disableView();
                }
            });
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->perPages([10, 20, 30, 40, 50]);
            $grid->paginate(env('Admin_Limit'));

        });
    }

    public function edit($id)
    {
        $http_refer = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : '';
        $goodsType = Goods::getGoodsType($id, $http_refer);
        $this->is_error = $goodsType['is_error'];
        $this->type = $goodsType['type'];
        $this->goodsstate = $goodsType['goodsstate'];
        $this->error_id = request('error_id');
        $this->gid = $id;
        //Goods::addErrorInfo(request('error_id'), $id);
        return Admin::content(function (Content $content) use ($id) {
            $content->header('商品管理');
            $content->description('商品管理...');
            $content->body($this->form()->edit($id));
        });
    }

    protected function form()
    {
        return Admin::form(Goods::class, function (Form $form) {
            $form->display('id', 'ID');  //
            $form->display('userid', '用户ID');
            $form->hidden('id');  //
            $form->hidden('goodsid');  //
            $form->hidden('goodstype');  //
            $form->text('goodstitle', '标题');
            $form->display('goodslink', '商品链接');//
            $form->radio('begintimetype', '开始时间类型')->options(['2' => '预约时间', '1' => '立即开始']);
            $form->datetime('begintime', '开始时间')->format('YYYY-MM-DD HH:mm:ss');
            $form->radio('goodcoupon.coupontype', '优惠券类型')->options(['2' => '阿里妈妈优惠券']);
            $form->radio('goodsshop.activitytype', '活动类型')->options(['0' => '无', '1' => '聚划算', '2' => '淘抢购']);
            //$form->multipleImage('coverimage', '主封面')->removable();//
            $form->multipleImage('copywritingimage', '文案图片')->removable();
            $form->currency('origprice', '商品原价')->symbol('￥');
            $form->currency('voucherprice', '劵后价')->symbol('￥');
            $form->text('goodcoupon.couponlink', '优惠券链接');
            $form->number('goodcoupon.coupontotal', '优惠券总量')->max(100000000);
            $form->rate('commissionrate', '佣金比例');
            $form->radio('commissiontype', '佣金类型')->options(['1' => '通用', '2' => '定向', '3' => '鹊桥', '4' => '营销']);
            $form->disableReset();
            $form->embeds('coverimage', function ($form) {
                $form->image('main', '主封面图片');
            });
            $form->embeds('copywriting', function ($form) {
                $form->ckeditor('first', '导购文案');
                $form->ckeditor('second', '二段导购文案');
            });
            if ($this->goodsstate == 3) {
                $good = Goods::where(['id' => $this->gid])->first();
                $failreason = Goods::getFailReason(1);
                $index = Goods::getFailReasonIndex($failreason, $good->refuse);
                $form->radio('content', '打回原因')->options($failreason)->default($index);
            }
            if (!$this->error_id) {
                if ($this->type == 1) {  //已通过
                    if ($this->goodsstate == 9 || $this->is_error) {
                        $opention = [4 => '下架', 9 => '商品纠错'];
                        $default = 9;
                    } else {
                        $opention = [4 => '下架', 20 => '更新商品信息'];
                        $default = 20;
                    }
                    $form->select('goodsstate', '商品审核')->options($opention)->rules('required', [
                        'required' => '商品审核必填',
                    ])->default($default);
                    $form->radio('content', '打回原因')->options(Goods::getFailReason(1));
                    $form->radio('integral', '是否扣分')->options(Goods::getIntegral());
                    $form->hidden('id');
                    $form->hidden('userid');
                    if ($this->is_error) {
                        $is_set_error_type = GoodsCorrection::getGoodsErrorType($this->gid);
                        $form->checkbox('is_set_error_type', '存在错误类型')->options(GoodsCorrection::getErrorType())->default($is_set_error_type);
                        $form->checkbox('error_type', '已处理类型')->options(GoodsCorrection::getErrorType());
                    }
                } elseif ($this->type == 2 || $this->type == 4) {  //拒绝

                } else {  //未审核
                    $opention = [2 => '通过', 3 => '拒绝'];
                    $form->select('goodsstate', '商品审核')->options($opention)->rules('required', [
                        'required' => '商品审核必填',
                    ]);
                    $form->radio('content', '打回原因')->options(Goods::getFailReason(1));
                    $form->radio('integral', '是否扣分')->options(Goods::getIntegral());
                    $form->hidden('id');
                    $form->hidden('userid');
                    // $form->ignore(['content', 'integral']);
                }
            } else {
                $goods_info = Goods::where(['id' => $this->gid])->first();
                if ($goods_info->goodsstate != 9) {
                    $opention = [$goods_info->goodsstate => '不做修改', 4 => '下架'];
                    $default = $goods_info->goodsstate;
                } else {
                    $opention = [9 => '不做修改', 4 => '下架'];
                    $default = 9;
                }
                $form->select('goodsstate', '商品审核')->options($opention)->default($default)->rules('required', [
                    'required' => '商品审核必填',
                ]);
                $is_set_error_type = GoodsCorrection::getGoodsErrorType($this->gid);
                $form->checkbox('is_set_error_type', '存在错误类型')->options(GoodsCorrection::getErrorType())->default($is_set_error_type);
                $form->checkbox('error_type', '已处理类型')->options(GoodsCorrection::getErrorType());
            }
            $form->ignore(['error_type', 'is_set_error_type', 'content', 'integral']);
            $form->tools(function (Form\Tools $tools) {
                $tools->disableBackButton();
                $tools->disableListButton();
                $tools->disableDelete();
                $tools->disableView();
            });
            $form->saving(function (Form $form) {
                if (request('goodsstate') == 3 && request('content') == 0) {
                    $error = new MessageBag([
                        'title' => '请选择拒绝原因!',
                    ]);
                    return back()->with(compact('error'));
                }
                $goods = Goods::where(['id' => request('id')])->first();
                if (($goods->goodsstate != 2)) {
                    $goods = Goods::where(['goodsid' => request('goodsid'), 'goodsstate' => 2])->where('userid', '>', 10000)->first();
                    if ($goods) {
                        $error = new MessageBag([
                            'title' => '该商品线上已存在,不能审核通过!!',
                        ]);
                        return back()->with(compact('error'));
                    }
                }
            });
            $form->saved(function (Form $form) {
                $gid = $form->model()->id;
                $goods = Goods::where(['id' => $gid])->first();
                $is_error = GoodsCorrection::getGoodsError($gid);
                if ($goods->site_error_status || $goods->auto_error_status || $is_error || $goods->goodsstate == 9) {
                    DB::beginTransaction();
                    if (request('goodsstate') == 4) {
                        if ($goods->goodsstate == 9) {
                            $model = StatisticsGoodsInfo::lastModel($goods->goodstype);
                            $bool = StatisticsGoodsInfoLog::saveGoodsInfoLog(4, $goods->goodstype, $gid, 1, $model->toArray(), 9);
                        } else {
                            $bool = StatisticsGoodsInfo::updateStatisticsGoods($gid, $goods->goodstype, request('goodsstate'), 1, $goods->created_at, $goods->goodsstate, false, 1);
                        }
                    } else {
                        $bool = GoodsCorrection::updateErrorStatus($gid, request('error_type'), request('goodsstate'));
                    }
                    if ($bool) {
                        DB::commit();
                    } else {
                        DB::rollBack();
                    }
                    return redirect('/admin/goodscorrection?t=already');
                } elseif (in_array($goods->goodsstate, [20])) {
                    $goods = Goods::where(['id' => $gid])->first();
                    $goods->goodsstate = 2;
                    $goods->save();
                } else {
                    Goods::save_log($gid, $form->model()->goodsstate, request('content'), request('integral'));  //save_log
                }
            });
        });
    }

    public function show($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header($this->headerStr . '管理');
            $content->description('编辑' . $this->headerStr);
            $content->body($this->form()->edit($id));
        });
    }

    public function uploadImage($request, $file_name)
    {
        if ($request->hasFile($file_name)) {
            $file = $request->file($file_name);
            $disk = QiniuStorage::disk('qiniu');
            $fileName = md5($file->getClientOriginalName() . time() . rand()) . '.' . $file->getClientOriginalExtension();
            $bool = $disk->put('web/image_' . $fileName, file_get_contents($file->getRealPath()));
            // 判断是否上传成功
            if ($bool) {
                $path = $disk->downloadUrl('web/image_' . $fileName);
                return $path;
            }
            return '';
        }
    }
}